// app == application 应用的意思
//引入核心模块
const http = require('http');
const fs = require('fs');
const url = require('url');
//第三方模块
const template = require('art-template'); //模板引擎
//注册模板引擎过滤器
template.defaults.imports.dateFormat = function(date, pattern) {
	var date = new Date(date),
		//年
		y = date.getFullYear(),
		//月
		m = date.getMonth() + 1,
		//日
		d = date.getDate(),
		//时
		hh = date.getHours(),
		//分
		mm = date.getMinutes(),
		//秒
		ss = date.getSeconds();
	if (pattern.toLoweerCase === 'yyyy-mm-dd') {
		return `${y}-${m}-${d}`;
	} else {
		return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
	}
};
//业务逻辑
http.createServer(async (req, res) => {
	let requrl = req.url;
	let data = '';
	let comments = null;
    let urlObj = new URL(requrl, 'http://127.0.0.1:3000');
    let database_address = './test_database/db.json';
	//请求根路径
	if (requrl === '/' || requrl === '/index') {
		comments = await read(database_address);
		data = await read('./view/home.html');
		res.end(render(data.toString(), JSON.parse(comments)));
	} else if (startWith(requrl, '/public/')) {
		//处理public目录静态资源可访问
		data = await read('.' + requrl);
		res.end(data);
	} else if (requrl === '/post/') {
		//发表留言页面
		data = await read('./view/post-massage.html');
		res.end(data);
	} else if (urlObj.pathname === '/submit_comments') {
		//提交留言
		let comment = {
			name: urlObj.searchParams.get('username'),
			add_time: new Date(),
			content: urlObj.searchParams.get('comment_content')
		};
		// return console.log(comment)
		data = await write_db(comment);
		if (data) {
			res.statusCode = 302;
			res.setHeader('Location', '/');
			res.end('success');
		} else {
			res.end('fail');
		}
	} else {
		//资源链接无效404
		data = await read('./view/404.html');
		res.end(data);
	}
}).listen(3000, () => {
	console.log('application is running at http://127.0.0.1:3000');
});

/**
 *  读取文件功能函数
 *
 * @param {String} path 读取的文件路径
 * @returns 文件内容
 */
function read(path) {
	return new Promise(resolve => {
		fs.readFile(path, (err, data) => {
			if (err) return console.log('文件读取失败');
			resolve(data);
		});
	});
}

/**
 * 判断一个字符串是否以另一个字符串开头
 *
 * @param {*} str 需要判断的字符串
 * @param {*} startStr 开始的字符串
 * @returns bool 一个字符串是否以另一个字符串开头
 */
function startWith(str, startStr) {
	return str.indexOf(startStr) == 0 ? true : false;
}

/**
 * 模板渲染
 *
 * @param {*} _template 模板字符串
 * @param {*} data 数据
 * @returns {String} 渲染了数据的字符串
 */
function render(_template, data) {
	return template.render(_template, {
		comments: data
	});
}

/**
 * 添加留言到本地储存
 *
 * @param {*} comment 留言
 * @returns {Boolean} 添加成功或失败
 */
async function write_db(comment) {
	let comments = JSON.parse(await read(database_address));
	comments.unshift(comment);
	return new Promise(resolve => {
		fs.writeFile(database_address, JSON.stringify(comments), err => {
			if (err) return console.log('数据写入失败');
			resolve(true);
		});
	});
}
